<?php

namespace App\Admin\Controllers;

use App\Admin\Models\Goods;
use Field\Interaction\FieldSubscriberTrait;
use Field\Interaction\FieldTriggerTrait;
use Illuminate\Http\Request;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Show;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use function foo\func;

class GoodsController extends AdminController
{

    use FieldTriggerTrait;
    use FieldSubscriberTrait;

    protected $title = '商品管理';

    protected function grid()
    {
        $grid = new Grid(new Goods);
        $grid->disableExport();
        $grid->model()->orderBy('sort', 'desc');
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
//            $actions->disableEdit();
//            $actions->disableDelete();
        });
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();

            $filter->column(1 / 3, function ($filter) {
                $filter->equal('goods_number', '商品编号');
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('is_owner', '归属地/号码状态')->select([
                    0 => '可选归属地',
                    1 => '不可选归属地'
                ]);
            });
//            $filter->column(1/2, function ($filter) {
//                $filter->between('created_at', '上架时间')->datetime();
//            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('is_sale', '商品状态')->select([
                    'on' => '上架',
                    'off' => '下架'
                ]);
            });
        });
        $grid->numbers('序号');
        $grid->rows(function ($row, $numbers) {
            $page = request('page');
            if ($page) {
                $page = ($page - 1) * 10;
            }
            $row->column('numbers', $page + $numbers + 1);
        });
        $grid->column('name', '商品名称');
        $grid->column('goods_number', '商品编号');
        $grid->column('skus', '商品描述')->display(function ($skus) {
            if (strlen($skus) > 10) {
                return mb_substr($skus, 0, 10) . '...';
            } else {
                return $skus;
            }
        });
        $grid->column('thump', '商品缩略图')->lightbox(['width' => 40, 'height' => 40]);
        $grid->column('operator', '运营商')->using(['1' => '移动', '2' => '联通', '3' => '电信']);
//        $grid->column('number','号卡号码');
        $grid->column('price', '套餐价格');
        $grid->column('zearnings', '直推返佣');
        $grid->column('jearnings', '间推返佣');
        $grid->column('detail', '详情图')->lightbox(['width' => 40, 'height' => 40]);
        $grid->column('background_img', '二维码背景图')->lightbox(['width' => 40, 'height' => 40]);
        $grid->column('is_earnings', '是否返佣')->display(function ($is_earnings) {
            switch ($is_earnings) {
                case 1:
                    return "返";
                    break;
                case 0:
                    return "不返";
                    break;
            }
        });
        $grid->column('earnings_condition', '返佣条件')->display(function ($earnings_condition) {
            if (strlen($earnings_condition) > 10) {
                return mb_substr($earnings_condition, 0, 10) . '...';
            } else {
                return $earnings_condition;
            }
        });
        $grid->column('is_owner', '归属地/号码状态')->display(function ($is_owner) {
            switch ($is_owner) {
                case 1:
                    return "不可选";
                    break;
                case 0:
                    return "可选";
                    break;
            }
        });
        $grid->column('owner_place', '商品归属地')->display(function ($owner_place) {
            if ($owner_place) {
                $arr = config('move.ownership');
                return (isset($arr[$owner_place])) ? $arr[$owner_place] : '未知归宿地';
            } else {
                return '无归属地';
            }
        });
        $grid->column('sort', '排序');
        $grid->column('is_sale', '是否上架')->display(function ($is_owner) {
            switch ($is_owner) {
                case 'on':
                    return "上架";
                    break;
                case 'off':
                    return "下架";
                    break;
            }
        });
//        $is_sale = [
//            'on'  => ['value' => 'on', 'text' => '上架', 'color' => 'primary'],
//            'off' => ['value' => 'off', 'text' => '下架', 'color' => 'default'],
//        ];
//        $grid->column('is_sale','是否上架')->switch($is_sale);
        return $grid;
    }

    protected function detail($id)
    {
        $show = new Show(Goods::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    protected function form()
    {
        $form = new Form(new Goods);
        //判断修改的时候套餐是否选择错误
        $form->saving(function (Form $form) {
            $id = $form->model()->id;
            if ($form->unusual_info) {
                $form->unusual_info = str_replace('，', ',', $form->unusual_info);
                $form->unusual_info = str_replace('；', ';', $form->unusual_info);
            }
            if ($id) {
                $prod1 = $form->prod;
                $ginfo = DB::table('shop_goods')->whereId($id)->first();
                if ($prod1 != $ginfo->prod) {
                    $operator = '';
                    if ($form->operator == 1) {
                        $operator = '移动';
                    } elseif ($form->operator == 2) {
                        $operator = '联通';
                    } else {
                        $operator = '电信';
                    }
                    return back()->with(admin_toastr('本次修改的套餐为' . $operator . '运营商下的' . $ginfo->name . ', 请确认是否选择正确', 'error'));
                }
            }
            //是否返佣
            if ($form->is_earnings == 1) {
                if ($form->zearnings == '' || $form->jearnings == '' || $form->earnings_condition == '') {
                    return back()->with(admin_toastr('返佣产品但是返佣内容填写不完整，请重新填写并确认数据完整性', 'error'));
                }
            } elseif ($form->is_earnings == 0) {
                $form->zearnings = 0;
                $form->jearnings = 0;
                $form->earnings_condition = '';

            }
            //是否有归属地 1: 有, 0: 无
            if ($form->is_owner == 0) {
                $form->owner_place = '';
            } elseif ($form->is_owner == 1) {
                if (!$form->owner_place) {
                    return back()->with(admin_toastr('请选择归属地', 'error'));
                }
            }


        });

        $operate = [1 => '移动', 2 => '联通', 3 => '电信'];
        if (request()->route()->getActionMethod() == 'edit') {
            $form->select('operator', '运营商')->options($operate)->readonly();
            $form->text('name', '商品名称')->readonly();
            $form->text('prod', '套餐编号')->readonly();
        } else {
            $form->select('operator', '运营商')->options($operate)->load('name', '/api/getGoodsPlan')->required();

            $form->select('name', '商品名称')->rules(function ($form) {
                if (!$id = $form->model()->id) {
                    return 'unique:shop_goods,prod';
                }
            }, ['商品套餐已录入'])->load('prod', '/api/getGoodsPlanid')->required();

            $form->select('prod', '套餐编号')->required();
        }


        $form->text("goods_number", '商品编号')->rules(function ($form) {
            if (!$id = $form->model()->id) {
                return 'unique:shop_goods,goods_number';
            }
        }, ['商品编号已存在'])->required();
        $form->image('thump', '商品缩略图')->move('uploads/goods_image')->uniqueName()->required();
        $form->text('skus', '商品描述')->rules('required|min:1', ['描述不能为空'])->required();
//        $form->text("number",'卡号')->rules('required|min:1',['请填写卡号'])->required();
        $form->text('sort', '商品排序')->placeholder('请填写排序号，值越大越靠前');
        $form->currency('price', '套餐价格')->symbol('￥')->required();
        $form->radio('is_sale', '是否上架')->options(['on' => '上架', 'off' => '下架'])->default('on')->required();
        $form->radio('is_earnings', '是否返佣')->options(['0' => '否', '1' => '返'])->checked()->default(1)->required();
        $form->currency('zearnings', '直推返佣')->symbol('￥');
        $form->currency('jearnings', '间推返佣')->symbol('￥');
        $form->textarea('earnings_condition', '返佣完成条件');
        $form->radio('is_owner', '有无归属地')->options(['0' => '无', '1' => '有'])->default(0)->checked()->required();
        $form->select('owner_place', '商品归属地')->options(config("move.ownership"));
        $form->image('detail', '详情图')->move('uploads/goods_image')->uniqueName()->required();
        $form->image('background_img', '二维码背景图')->move('uploads/goods_image')->uniqueName()->required();
        $form->text('unusual_info', '异常地址')->placeholder('格式:河南,郑州;云南;河南,上蔡');


        //触发事件的Script对象
        $triggerScript = $this->createTriggerScript($form);
        //接收并处理事件的Script对象
        $subscribeScript = $this->createSubscriberScript($form, function ($builder) {
            // 添加事件响应函数
            $builder->subscribe('is_earnings', 'checked', function ($event) {

                // 这里填写处理事件的javascript脚本，注意：一定要返回一个完整的 javascript function ，否则报错！！！！
                return <<< EOT

            // function中的参数data，是事件自带数据，方便做逻辑处! data会因为事件不同而类型不同，具体可以在chrome中的console中查看。
       function(data){
          console.log ('catch an event -> {$event}');
          // 某个控件对于某个事件做出处理， 

          //.... 事件处理 ....
          console.log(data);
          var t1 = document.getElementById('zearnings').parentElement.parentElement.parentElement;
          var t2 = document.getElementById('jearnings').parentElement.parentElement.parentElement;
          var t3 = document.getElementsByName("earnings_condition")[0].parentElement.parentElement;
          if (data == 1) {
                t1.style.display = 'block';
                t2.style.display = 'block';
                t3.style.display = 'block'; 
          } else {
                t1.style.display = 'none'; 
                t2.style.display = 'none'; 
                t3.style.display = 'none'; 
          }
       }

EOT;
            });
        });

        // 最后把 $triggerScript 和 $subscribeScript 注入到Form中去。
        $form->scriptinjecter('name_no_care', $triggerScript, $subscribeScript);


        return $form;
    }
}
